// Dashboard管理类
class DashboardManager {
    constructor(readApiUrl) {
        this.readApiUrl = readApiUrl;
        this.isRealTime = false; // 默认使用模拟数据
        this.statusElement = null;
        this.charts = {}; // 存储图表实例
        this.currentProcessTab = 'plan'; // 当前工序统计tab
        this.init();
    }

    init() {
        this.createDataSourceStatus();
        this.loadAllData();
        this.setupEventListeners();
        this.startRealTimeUpdates();
    }

    // 创建数据源状态显示
    createDataSourceStatus() {
        this.statusElement = document.createElement('div');
        this.statusElement.id = 'dataSourceStatus';
        this.updateDataSourceStatus();
        document.body.appendChild(this.statusElement);
    }

    // 更新数据源状态
    updateDataSourceStatus() {
        // 不显示任何状态指示器
        if (this.statusElement) {
            this.statusElement.style.display = 'none';
        }
    }

    // 设置事件监听器
    setupEventListeners() {
        // 全屏切换
        document.getElementById('fullscreenBtn')?.addEventListener('click', () => {
            if (document.fullscreenElement) {
                document.exitFullscreen();
            } else {
                document.documentElement.requestFullscreen();
            }
        });

        // 工序统计tab切换
        document.querySelectorAll('.process-tab').forEach(tab => {
            tab.addEventListener('click', (e) => {
                const tabType = e.target.getAttribute('data-tab');
                this.switchProcessTab(tabType);
            });
        });
    }

    // 开始实时更新
    startRealTimeUpdates() {
        if (this.isRealTime) {
            // 每30秒更新一次数据
            setInterval(() => {
                this.loadAllData();
            }, 30000);
        }
    }

    // 加载所有数据
    async loadAllData() {
        try {
            if (this.isRealTime) {
                // 实时数据模式
                await Promise.all([
                    this.loadDefectiveRate(),
                    this.loadProductionSummary(),
                    this.loadEmployeePerformance(),
                    this.loadDailyProduction(),
                    this.loadProcessStats(),
                    this.loadSalesOrderSummary(),
                    this.loadDefectiveItemRank(),
                    this.loadCumulativeData(),
                    this.loadTrendData()
                ]);
            } else {
                // 模拟数据模式
                this.loadMockData();
            }
        } catch (error) {
            console.error('加载数据失败:', error);
            // 如果实时数据加载失败，回退到模拟数据
            if (this.isRealTime) {
                console.log('回退到模拟数据模式');
                this.isRealTime = false;
                this.updateDataSourceStatus();
                this.loadMockData();
            }
        }
    }

    // 加载不良品率统计
    async loadDefectiveRate() {
        try {
            const response = await fetch(`/Dashboard/GetDefectiveRate?days=7`);
            const result = await response.json();
            console.log('不良品率数据:', result);
            
            if (result.success && result.data) {
                const data = result.data;
                this.updateElement('defectiveRate', `${data.defectiveRate}%`, '.defect-rate-value');
                
                // 更新实时指标中的不良率
                const defectElement = document.querySelector('.metric-card.defect .metric-value');
                if (defectElement) {
                    defectElement.textContent = `${data.defectiveRate}%`;
                }
            }
        } catch (error) {
            console.error('加载不良品率失败:', error);
        }
    }

    // 加载生产统计汇总
    async loadProductionSummary() {
        try {
            const response = await fetch(`/Dashboard/GetProductionSummary?days=30`);
            const result = await response.json();
            console.log('生产统计汇总数据:', result);
            
            if (result.success && result.data) {
                const data = result.data;
                this.updateElement('totalGoodQuantity', data.totalGoodQuantity);
                this.updateElement('totalBadQuantity', data.totalBadQuantity);
                this.updateElement('goodRate', `${data.goodRate}%`);
                this.updateElement('totalWorkOrders', data.totalWorkOrders);
                
                // 更新实时指标中的良品率
                this.updateElement('qualityRate', `${data.goodRate}%`);
            }
        } catch (error) {
            console.error('加载生产统计汇总失败:', error);
        }
    }

    // 加载员工绩效Top5
    async loadEmployeePerformance() {
        try {
            const response = await fetch(`/Dashboard/GetEmployeePerformance?days=30`);
            const result = await response.json();
            console.log('员工绩效数据:', result);
            
            if (result.success && result.data) {
                this.renderEmployeePerformance(result.data);
            }
        } catch (error) {
            console.error('加载员工绩效失败:', error);
        }
    }

    // 渲染员工绩效
    renderEmployeePerformance(data) {
        const container = document.querySelector('.performance-list');
        if (!container) return;

        if (data.length === 0) {
            container.innerHTML = '<div style="text-align: center; color: #a0c4ff; padding: 20px;">暂无数据</div>';
            return;
        }

        container.innerHTML = data.map((item, index) => `
            <div class="performance-item">
                <span class="rank">${index + 1}</span>
                <span class="name">${item.employeeName || '未知'}</span>
                <span class="score">${item.efficiencyScore}%</span>
            </div>
        `).join('');
    }

    // 加载日生产明细
    async loadDailyProduction() {
        try {
            const response = await fetch(`/Dashboard/GetDailyProduction?days=7`);
            const result = await response.json();
            console.log('日生产明细数据:', result);
            
            if (result.success && result.data) {
                this.renderDailyProductionTable(result.data);
            }
        } catch (error) {
            console.error('加载日生产明细失败:', error);
        }
    }

    // 渲染日生产明细表格
    renderDailyProductionTable(data) {
        const tbody = document.querySelector('.production-statistics-table tbody');
        if (!tbody) return;

        if (data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #a0c4ff;">暂无数据</td></tr>';
            return;
        }

        tbody.innerHTML = data.map(item => `
            <tr>
                <td>${new Date(item.productionDate).toLocaleDateString()}</td>
                <td>${item.productName}</td>
                <td>${item.plannedQuantity}</td>
                <td>${item.goodQuantity}</td>
                <td>${item.badQuantity}</td>
                <td>${item.completionRate}%</td>
            </tr>
        `).join('');
    }

    // 加载工序统计
    async loadProcessStats() {
        try {
            const [planResponse, reportResponse] = await Promise.all([
                fetch(`/Dashboard/GetProcessPlanRank?days=30`),
                fetch(`/Dashboard/GetProcessReportRank?days=30`)
            ]);

            const planResult = await planResponse.json();
            const reportResult = await reportResponse.json();
            console.log('工序计划数据:', planResult);
            console.log('工序报工数据:', reportResult);

            this.processData = {
                plan: planResult.success ? planResult.data : [],
                report: reportResult.success ? reportResult.data : []
            };

            this.renderProcessStats();
        } catch (error) {
            console.error('加载工序统计失败:', error);
        }
    }

    // 切换工序统计tab
    switchProcessTab(tabType) {
        this.currentProcessTab = tabType;
        
        // 更新tab样式
        document.querySelectorAll('.process-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tabType}"]`)?.classList.add('active');

        // 渲染对应数据
        this.renderProcessStats();
    }

    // 渲染工序统计
    renderProcessStats() {
        const container = document.getElementById('processContent');
        if (!container || !this.processData) return;

        const data = this.processData[this.currentProcessTab] || [];
        
        if (data.length === 0) {
            container.innerHTML = '<div style="text-align: center; color: #a0c4ff; padding: 20px;">暂无数据</div>';
            return;
        }

        const isReport = this.currentProcessTab === 'report';
        
        container.innerHTML = data.map(item => `
            <div class="process-item">
                <span class="name">${item.processName}</span>
                <span class="value">${isReport ? item.totalReportedQuantity : item.totalPlannedQuantity}</span>
            </div>
        `).join('');
    }

    // 加载销售订单统计
    async loadSalesOrderSummary() {
        try {
            const response = await fetch(`/Dashboard/GetSalesOrderSummary?days=30`);
            const result = await response.json();
            console.log('销售订单统计数据:', result);
            
            if (result.success && result.data) {
                const data = result.data;
                this.updateElement('totalOrders', data.totalOrders);
                this.updateElement('totalProducts', data.totalProducts);
                this.updateElement('orderCompletionRate', `${data.orderCompletionRate}%`);
            }
        } catch (error) {
            console.error('加载销售订单统计失败:', error);
        }
    }

    // 加载不良品分布Top5
    async loadDefectiveItemRank() {
        try {
            const response = await fetch(`/Dashboard/GetDefectiveItemRank?days=30&top=5`);
            const result = await response.json();
            console.log('不良品分布数据:', result);
            
            if (result.success && result.data) {
                this.renderDefectiveItemRank(result.data);
            }
        } catch (error) {
            console.error('加载不良品分布失败:', error);
        }
    }

    // 渲染不良品分布Top5
    renderDefectiveItemRank(data) {
        // 尝试两种不同的容器选择器
        const container = document.querySelector('.defective-top5-list') || document.querySelector('.defective-rank-list');
        if (!container) return;

        if (data.length === 0) {
            container.innerHTML = '<div style="text-align: center; color: #a0c4ff; padding: 20px;">暂无数据</div>';
            return;
        }

        container.innerHTML = data.map((item, index) => `
            <div class="defective-item">
                <span class="rank">${index + 1}</span>
                <span class="name">${item.defectiveItemName || 'null'}</span>
                <span class="percentage">${item.avgPercentage}%</span>
            </div>
        `).join('');
    }

    // 加载累计数据
    async loadCumulativeData() {
        try {
            const response = await fetch(`/Dashboard/GetCumulativeData`);
            const result = await response.json();
            console.log('累计数据:', result);
            
            if (result.success && result.data) {
                const data = result.data;
                // 更新实时指标
                this.updateElement('dailyOutput', data.cumulativeUnitsData);
                
                // 计算效率分数（示例）
                const efficiency = data.cumulativeQualifiedData > 0 ? 
                    Math.round((data.cumulativeQualifiedData / (data.cumulativeQualifiedData + data.cumulativeUnqualifiedData)) * 100) : 0;
                this.updateElement('efficiency', `${efficiency}%`);
            }
        } catch (error) {
            console.error('加载累计数据失败:', error);
        }
    }

    // 加载趋势数据
    async loadTrendData() {
        try {
            // 使用日生产明细数据来生成趋势图
            const response = await fetch(`/Dashboard/GetDailyProduction?days=7`);
            const result = await response.json();
            
            if (result.success && result.data) {
                this.renderTrendChart(result.data);
            }
        } catch (error) {
            console.error('加载趋势数据失败:', error);
        }
    }

    // 渲染趋势图表
    renderTrendChart(data) {
        const chartElement = document.getElementById('trendChart');
        if (!chartElement) return;

        // 如果图表已存在，先销毁
        if (this.charts.trendChart) {
            this.charts.trendChart.destroy();
        }

        if (data.length === 0) {
            const ctx = chartElement.getContext('2d');
            ctx.clearRect(0, 0, chartElement.width, chartElement.height);
            ctx.fillStyle = '#a0c4ff';
            ctx.font = '14px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('暂无数据', chartElement.width / 2, chartElement.height / 2);
            return;
        }

        // 处理数据：按日期分组汇总
        const groupedData = data.reduce((acc, item) => {
            const date = new Date(item.productionDate).toLocaleDateString();
            if (!acc[date]) {
                acc[date] = { goodQuantity: 0, totalQuantity: 0 };
            }
            acc[date].goodQuantity += item.goodQuantity;
            acc[date].totalQuantity += item.goodQuantity + item.badQuantity;
            return acc;
        }, {});

        const dates = Object.keys(groupedData).sort();
        const outputData = dates.map(date => groupedData[date].goodQuantity);
        const qualityData = dates.map(date => {
            const total = groupedData[date].totalQuantity;
            return total > 0 ? Math.round((groupedData[date].goodQuantity / total) * 100) : 0;
        });

        const ctx = chartElement.getContext('2d');
        this.charts.trendChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: dates,
                datasets: [{
                    label: '日产量',
                    data: outputData,
                    borderColor: '#4CAF50',
                    backgroundColor: 'rgba(76, 175, 80, 0.1)',
                    tension: 0.4,
                    yAxisID: 'y'
                }, {
                    label: '良品率(%)',
                    data: qualityData,
                    borderColor: '#2196F3',
                    backgroundColor: 'rgba(33, 150, 243, 0.1)',
                    tension: 0.4,
                    yAxisID: 'y1'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        labels: {
                            color: '#fff',
                            font: { size: 11 }
                        }
                    }
                },
                scales: {
                    x: {
                        ticks: {
                            color: '#fff',
                            font: { size: 10 }
                        },
                        grid: {
                            color: 'rgba(255, 255, 255, 0.1)'
                        }
                    },
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        ticks: {
                            color: '#fff',
                            font: { size: 10 }
                        },
                        grid: {
                            color: 'rgba(255, 255, 255, 0.1)'
                        }
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        ticks: {
                            color: '#fff',
                            font: { size: 10 }
                        },
                        grid: {
                            drawOnChartArea: false,
                        }
                    }
                }
            }
        });
    }

    // 添加模拟数据来填充实时指标
    loadMockRealTimeData() {
        // 加载所有模拟数据
        this.loadMockDefectiveRate();
        this.loadMockProductionSummary();
        this.loadMockEmployeePerformance();
        this.loadMockDailyProduction();
        this.loadMockProcessStats();
        this.loadMockSalesOrderSummary();
        this.loadMockDefectiveItemRank();
        this.loadMockCumulativeData();
        this.loadMockWorkOrderEfficiency();
        this.loadMockTrendData();
        
        // 设备利用率
        this.updateElement('equipmentUtilization', '95%');
        
        // 在线人数
        this.updateElement('onlinePersonnel', '25');
        
        // 工作效率
        this.updateElement('efficiency', '92%');
        
        // 日产量
        this.updateElement('dailyOutput', '38');
    }

    // 模拟不良品率数据
    loadMockDefectiveRate() {
        const mockData = {
            success: true,
            data: {
                totalDefective: 8,
                totalProduced: 60,
                defectiveRate: 13.33,
                dateRange: "最近7天"
            }
        };
        
        console.log('不良品率数据:', mockData);
        if (mockData.success && mockData.data) {
            const data = mockData.data;
            this.updateElement('defectiveRate', `${data.defectiveRate}%`, '.defect-rate-value');
            
            // 更新实时指标中的不良率
            const defectElement = document.querySelector('.metric-card.defect .metric-value');
            if (defectElement) {
                defectElement.textContent = `${data.defectiveRate}%`;
            }
        }
    }

    // 模拟生产统计汇总数据
    loadMockProductionSummary() {
        const mockData = {
            success: true,
            data: {
                totalGoodQuantity: 52,
                totalBadQuantity: 8,
                goodRate: 86.67,
                totalWorkOrders: 4
            }
        };
        
        console.log('生产统计汇总数据:', mockData);
        if (mockData.success && mockData.data) {
            const data = mockData.data;
            this.updateElement('totalGoodQuantity', data.totalGoodQuantity);
            this.updateElement('totalBadQuantity', data.totalBadQuantity);
            this.updateElement('goodRate', `${data.goodRate}%`);
            this.updateElement('totalWorkOrders', data.totalWorkOrders);
            
            // 更新实时指标中的良品率
            this.updateElement('qualityRate', `${data.goodRate}%`);
        }
    }

    // 模拟员工绩效数据
    loadMockEmployeePerformance() {
        const mockData = {
            success: true,
            data: [
                {
                    employeeName: "系统管理员",
                    totalGoodQuantity: 52,
                    totalWorkTime: 480,
                    reportCount: 1,
                    efficiencyScore: 3.19
                },
                {
                    employeeName: "小",
                    totalGoodQuantity: 8,
                    totalWorkTime: 480,
                    reportCount: 1,
                    efficiencyScore: 1.67
                }
            ]
        };
        
        console.log('员工绩效数据:', mockData);
        if (mockData.success && mockData.data) {
            this.renderEmployeePerformance(mockData.data);
        }
    }

    // 模拟日生产明细数据
    loadMockDailyProduction() {
        const mockData = {
            success: true,
            data: [
                {
                    productionDate: "2025-08-19T00:00:00",
                    productName: "耳机转接头",
                    plannedQuantity: 30,
                    goodQuantity: 30,
                    badQuantity: 0,
                    completionRate: 100
                },
                {
                    productionDate: "2025-08-19T00:00:00",
                    productName: "手机壳转接头",
                    plannedQuantity: 10,
                    goodQuantity: 8,
                    badQuantity: 2,
                    completionRate: 100
                }
            ]
        };
        
        console.log('日生产明细数据:', mockData);
        if (mockData.success && mockData.data) {
            this.renderDailyProductionTable(mockData.data);
        }
    }

    // 模拟工序计划数据
    loadMockProcessPlanRank() {
        const mockData = {
            success: true,
            data: [
                {
                    processName: "激光切割",
                    totalPlannedQuantity: 100,
                    processCount: 2
                },
                {
                    processName: "打螺丝",
                    totalPlannedQuantity: 100,
                    processCount: 1
                },
                {
                    processName: "焊接装配",
                    totalPlannedQuantity: 100,
                    processCount: 1
                },
                {
                    processName: "金属加工",
                    totalPlannedQuantity: 50,
                    processCount: 1
                },
                {
                    processName: "金属加工",
                    totalPlannedQuantity: 0,
                    processCount: 1
                }
            ]
        };
        
        return mockData;
    }

    // 模拟工序报工数据
    loadMockProcessReportRank() {
        const mockData = {
            success: true,
            data: [
                {
                    processName: "机械加工",
                    totalReportedQuantity: 50,
                    reportCount: 1
                },
                {
                    processName: "电机组装",
                    totalReportedQuantity: 10,
                    reportCount: 1
                }
            ]
        };
        
        return mockData;
    }

    // 模拟销售订单统计数据
    loadMockSalesOrderSummary() {
        const mockData = {
            success: true,
            data: {
                totalOrders: 3,
                totalProducts: 233,
                orderCompletionRate: 85
            }
        };
        
        console.log('销售订单统计数据:', mockData);
        if (mockData.success && mockData.data) {
            const data = mockData.data;
            this.updateElement('totalOrders', data.totalOrders);
            this.updateElement('totalProducts', data.totalProducts);
            this.updateElement('orderCompletionRate', `${data.orderCompletionRate}%`);
        }
    }

    // 模拟不良品分布数据
    loadMockDefectiveItemRank() {
        const mockData = {
            success: true,
            data: [
                {
                    defectiveItemCode: "PD003",
                    defectiveItemName: "手机壳转接头",
                    totalQuantity: 5,
                    avgPercentage: 12
                },
                {
                    defectiveItemCode: "PD001",
                    defectiveItemName: "家电转接头",
                    totalQuantity: 2,
                    avgPercentage: 20
                }
            ]
        };
        
        console.log('不良品分布数据:', mockData);
        if (mockData.success && mockData.data) {
            this.renderDefectiveItemRank(mockData.data);
        }
    }

    // 模拟累计数据统计
    loadMockCumulativeData() {
        const mockData = {
            success: true,
            data: {
                cumulativeUnitsData: 670,
                productionPlanData: 1500,
                cumulativeQualifiedData: 0,
                cumulativeUnqualifiedData: 0
            }
        };
        
        console.log('累计数据:', mockData);
        if (mockData.success && mockData.data) {
            const data = mockData.data;
            this.updateElement('cumulativeUnitsData', data.cumulativeUnitsData);
            this.updateElement('productionPlanData', data.productionPlanData);
            this.updateElement('cumulativeQualifiedData', data.cumulativeQualifiedData);
            this.updateElement('cumulativeUnqualifiedData', data.cumulativeUnqualifiedData);
        }
    }

    // 模拟工序统计数据
    loadMockProcessStats() {
        // 根据当前tab加载不同数据
        if (this.currentProcessTab === 'plan') {
            const mockData = this.loadMockProcessPlanRank();
            if (mockData.success && mockData.data) {
                this.renderProcessRank(mockData.data, 'plan');
            }
        } else {
            const mockData = this.loadMockProcessReportRank();
            if (mockData.success && mockData.data) {
                this.renderProcessRank(mockData.data, 'report');
            }
        }
    }

    // 加载模拟工单效率数据
    loadMockWorkOrderEfficiency() {
        const mockData = [
            { workOrderCode: 'WO001', productName: '电机组件A', efficiency: 98 },
            { workOrderCode: 'WO002', productName: '控制器B', efficiency: 95 },
            { workOrderCode: 'WO003', productName: '传感器C', efficiency: 92 },
            { workOrderCode: 'WO004', productName: '电路板D', efficiency: 89 },
            { workOrderCode: 'WO005', productName: '外壳E', efficiency: 87 }
        ];

        const container = document.querySelector('.workorder-efficiency-list');
        if (!container) return;

        container.innerHTML = mockData.map((item, index) => `
            <div class="efficiency-item">
                <span class="rank">${index + 1}</span>
                <span class="workorder">${item.workOrderCode}</span>
                <span class="product">${item.productName}</span>
                <span class="efficiency">${item.efficiency}%</span>
            </div>
        `).join('');
    }

    // 模拟趋势数据
    loadMockTrendData() {
        const mockData = {
            success: true,
            data: [
                {
                    productionDate: "2025-08-19T00:00:00",
                    productName: "耳机转接头",
                    plannedQuantity: 30,
                    goodQuantity: 30,
                    badQuantity: 0,
                    completionRate: 100
                },
                {
                    productionDate: "2025-08-19T00:00:00",
                    productName: "手机壳转接头",
                    plannedQuantity: 10,
                    goodQuantity: 8,
                    badQuantity: 2,
                    completionRate: 100
                }
            ]
        };
        
        console.log('趋势数据:', mockData);
        if (mockData.success && mockData.data) {
            this.renderTrendChart(mockData.data);
        }
    }



    // 渲染工序排名
    renderProcessRank(data, type) {
        const container = document.querySelector('.process-rank-list');
        if (!container) return;

        if (data.length === 0) {
            container.innerHTML = '<div style="text-align: center; color: #a0c4ff; padding: 20px;">暂无数据</div>';
            return;
        }

        const quantityLabel = type === 'plan' ? '计划数' : '报工数';
        container.innerHTML = data.map((item, index) => `
            <div class="process-item">
                <span class="process-name">${item.processName || 'null'}</span>
                <span class="quantity">${type === 'plan' ? item.totalPlannedQuantity : item.totalReportedQuantity}</span>
            </div>
        `).join('');
    }

    // 加载模拟数据
    loadMockData() {
        console.log('加载模拟数据...');
        
        // 设置实时指标数据
        this.updateElement(null, '95%', '.metric-card.equipment .metric-value');
        this.updateElement(null, '86.67%', '.metric-card.quality .metric-value');
        this.updateElement(null, '92%', '.metric-card.efficiency .metric-value');
        this.updateElement(null, '38', '.metric-card.production .metric-value');
        this.updateElement(null, '25', '.metric-card.online .metric-value');
        this.updateElement(null, '13.33%', '.metric-card.defect .metric-value');
        
        // 设置生产统计汇总
        this.updateElement(null, '52', '.summary-value.good-quantity');
        this.updateElement(null, '8', '.summary-value.bad-quantity');
        this.updateElement(null, '86.67%', '.summary-value.good-rate');
        this.updateElement(null, '4', '.summary-value.total-orders');
        
        // 设置员工绩效Top5
        const performanceList = document.querySelector('.performance-list');
        if (performanceList) {
            performanceList.innerHTML = `
                <div class="performance-item">
                    <span class="rank">1</span>
                    <span class="name">系统管理员</span>
                    <span class="score">3.19%</span>
                </div>
                <div class="performance-item">
                    <span class="rank">2</span>
                    <span class="name">小</span>
                    <span class="score">1.67%</span>
                </div>
            `;
        }
        
        // 设置日生产明细表格
        const tbody = document.querySelector('.production-statistics-table tbody');
        if (tbody) {
            tbody.innerHTML = `
                <tr>
                    <td>2025/8/19</td>
                    <td>耳机转接头</td>
                    <td>30</td>
                    <td>30</td>
                    <td>0</td>
                    <td>100%</td>
                </tr>
                <tr>
                    <td>2025/8/19</td>
                    <td>手机壳转接头</td>
                    <td>10</td>
                    <td>8</td>
                    <td>2</td>
                    <td>100%</td>
                </tr>
            `;
        }
        
        // 设置工序统计数据
        this.processData = {
            plan: [
                { processName: '激光切割', totalPlannedQuantity: 150 },
                { processName: '打螺丝', totalPlannedQuantity: 120 },
                { processName: '焊接装配', totalPlannedQuantity: 100 }
            ],
            report: [
                { processName: '机械加工', totalReportedQuantity: 80 },
                { processName: '电机组装', totalReportedQuantity: 60 }
            ]
        };
        this.renderProcessStats(this.currentProcessTab);
        
        // 设置销售订单统计
        this.updateElement(null, '3', '.summary-value.total-orders-count');
        this.updateElement(null, '233', '.summary-value.total-products');
        this.updateElement(null, '85%', '.summary-value.completion-rate');
        
        // 设置不良品分布Top5
        const defectiveList = document.querySelector('.defective-top5-list');
        if (defectiveList) {
            defectiveList.innerHTML = `
                <div class="defective-item">
                    <span class="rank">1</span>
                    <span class="name">手机壳转接头</span>
                    <span class="rate">12%</span>
                </div>
                <div class="defective-item">
                    <span class="rank">2</span>
                    <span class="name">家电转接头</span>
                    <span class="rate">20%</span>
                </div>
            `;
        }
        
        // 设置工单效率Top5
        const workorderList = document.querySelector('.workorder-efficiency-list');
        if (workorderList) {
            workorderList.innerHTML = `
                <div class="workorder-item">
                    <span class="workorder-no">WO001</span>
                    <span class="process-name">机械加工A</span>
                    <span class="efficiency">95%</span>
                </div>
                <div class="workorder-item">
                    <span class="workorder-no">WO002</span>
                    <span class="process-name">装配测试</span>
                    <span class="efficiency">93%</span>
                </div>
                <div class="workorder-item">
                    <span class="workorder-no">WO003</span>
                    <span class="process-name">传感器C</span>
                    <span class="efficiency">92%</span>
                </div>
                <div class="workorder-item">
                    <span class="workorder-no">WO004</span>
                    <span class="process-name">电路板D</span>
                    <span class="efficiency">89%</span>
                </div>
                <div class="workorder-item">
                    <span class="workorder-no">WO005</span>
                    <span class="process-name">外壳</span>
                    <span class="efficiency">87%</span>
                </div>
            `;
        }
        
        // 初始化生产趋势图表
        this.initTrendChart();
        
        console.log('模拟数据加载完成');
    }

    // 更新元素内容
    updateElement(id, value, selector = null) {
        const element = selector ? document.querySelector(selector) : document.getElementById(id);
        if (element) {
            element.textContent = value;
        }
    }

    // 初始化生产趋势图表
    initTrendChart() {
        // 这里可以初始化图表，目前暂时留空
        // 如果需要图表功能，可以使用 Chart.js 或其他图表库
        console.log('生产趋势图表初始化完成');
    }
}

// 初始化Dashboard
document.addEventListener('DOMContentLoaded', function() {
    // 从页面获取API配置
    const readApiUrl = window.readApiUrl || 'https://localhost:5001/api';
    
    // 创建Dashboard管理器实例
    window.dashboardManager = new DashboardManager(readApiUrl);
    
    // 加载模拟实时数据
    window.dashboardManager.loadMockRealTimeData();
    
    // 实时时间更新
    function updateTime() {
        const now = new Date();
        const timeStr = now.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        });
        
        const timeElement = document.getElementById('currentTime');
        if (timeElement) {
            timeElement.textContent = timeStr;
        }
    }
    
    // 立即更新时间，然后每秒更新
    updateTime();
    setInterval(updateTime, 1000);
}); 